#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <memory.h>
#include "Base64.h"

const char coding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
typedef unsigned char byte;
byte function (byte number){
	int i = 0;
	byte index = 0;
	for(i = 0; i < 64; i++){
		if (coding[i] == number) {
			index = i;
		}
	}
	return index; 
}

void encode(FILE *pFile1, FILE *pFile2){
	byte input [3] = {0, 0, 0};
	byte output[4] = {0, 0, 0, 0};
	int i = 0;

	while(1){

		int count = fread(input, sizeof(byte), 3, pFile1);
		if (count == 0)
			break;

		output[0] = (input[0]>>2) & 0x3F;
		output[1] = (((input[1]>>4) & 0x0F) | ((input[0]<<4) & 0x30)) & 0x3F;
		output[2] = (((input[2]>>6) & 3) | ((input[1]<<2) & 0x3C)) & 0x3F;
		output[3] = input[2] & 0x3F;

		output[0] = coding[output[0]];
		output[1] = coding[output[1]];
		output[2] = coding[output[2]];
		output[3] = coding[output[3]];
		
		i++;

		fwrite(output, sizeof(byte), count+1, pFile2);
		fwrite("===", sizeof(byte), 3-count, pFile2);
		if (i == 19){
			fwrite("\n", sizeof(byte), 1, pFile2);
			i = 0;
		}
		input[0] = 0;
		input[1] = 0;
		input[2] = 0;

		memset(input, 0, 3);
		
	}
}
void decode(FILE *pFile1, FILE *pFile2){
	byte ch = 0;
	byte index = 0;
	int i = 0;
	byte input [4] = {0,0,0,0};
	byte output[3] = {0,0,0};
	byte var = 0;
	int count = 0;
	
	while(1){
		
		i = 0;
		do{
			var = getc(pFile1);
			if(var == EOF | var == '='){
				break;
			}
			if(var != '\n'){
				input[i] = var;
				i++;
			}
			/*else{
				getchar();
			}*/
		} while(i < 4);
		count = i;
		if (count == 0)
			break;
		for(i=0;i<4;i++){
			if (input[i] == '='){
				count = count - 1;
			}
		}
		/*for(i=0;i<5;i++){
			if (input[i] == "\n"){
				input[i] = input[i + 1];
			}
		}*/
		for (i = 0; i<4; i++){
			input[i] = function(input[i]);
		}
		
		output[0] = ((input[0]<<2) & 0xFC) | ((input[1]>>4) & 3);
		output[1] = ((input[1] << 4) & 0xF0) | ((input[2]>>2) & 0xF);
		output[2] = ((input[2]<<6) & 0xC0) | (input[3] & 0x3F);
					
		fwrite(output, sizeof(byte), count - 1, pFile2);
		memset(input, 0, 4);
		if(var == '='){
			break;
		} 
	}
}
	
